package folder

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"

	"gitee.com/ispace/core/infrastructure/common/dto"
	"gitee.com/ispace/core/infrastructure/common/gv"
)

type FolderMoveHandler struct {
	request dto.WsRequestDto
}

// Init 方法实现
func (h *FolderMoveHandler) Init(request dto.WsRequestDto) {
	h.request = request
}

// Execute 方法实现
func (h *FolderMoveHandler) Execute() dto.WsResponseDto {

	// step init:
	result := dto.WsResponseDto{}
	result.Header.Id = h.request.Header.Id

	// step 1: params
	bodyBytes, err := json.Marshal(h.request.Body)
	if err != nil {
		result.Header.Stat = 2
		result.Body = fmt.Sprintf("Error marshalling message:%s", err)
		return result
	}

	params := map[string]string{}
	err = json.Unmarshal(bodyBytes, &params)
	if err != nil {
		result.Header.Stat = 2
		result.Body = fmt.Sprintf("Error unmarshalling message:%s", err)
		return result
	}

	// step 2:
	err = h.move(params["srcPath"], params["destPath"])
	if err != nil {
		result.Header.Stat = 2
		result.Body = fmt.Sprintf("Error CreateFile message:%s", err)
		return result
	}

	// step end:
	result.Header.Stat = 200
	return result
}

// 移动文件夹
func (fh *FolderMoveHandler) move(srcPath, destPath string) error {
	srcPath = filepath.Join(gv.BasePath, srcPath)
	destPath = filepath.Join(gv.BasePath, destPath)
	srcInfo, err := os.Stat(srcPath)
	if err != nil {
		return fmt.Errorf("source path does not exist: %s", err)
	}
	if !srcInfo.IsDir() {
		return fmt.Errorf("source path is not a directory")
	}

	err = filepath.Walk(srcPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		// 构建目标路径
		relPath, err := filepath.Rel(srcPath, path)
		if err != nil {
			return err
		}
		destFilePath := filepath.Join(destPath, relPath)

		if info.IsDir() {
			// 创建目标目录
			if err := os.MkdirAll(destFilePath, info.Mode()); err != nil {
				return fmt.Errorf("failed to create destination directory: %s", err)
			}
		} else {
			// 移动文件
			if err := os.Rename(path, destFilePath); err != nil {
				return fmt.Errorf("failed to move file: %s", err)
			}
		}
		return nil
	})
	if err != nil {
		return fmt.Errorf("failed to move directory: %s", err)
	}

	// 删除源目录
	if err := os.RemoveAll(srcPath); err != nil {
		return fmt.Errorf("failed to remove source directory: %s", err)
	}

	return nil
}
